/**
 * @Description : 区域模块
 **/
const regionModel = require("../model/regionModel");
const { output } = require("../common/index");
const qs = require("qs");
const regionList = async (req, res) => {
    try {
        var count = 0;
        var list = {};
        var tmpMatch = { status: 1 };
        var tmpRequest = req.body ? qs.parse(req.body) : {}; //获取查询参数内容
        if (tmpRequest.searchForm) {
            let tmpSearch = JSON.parse(tmpRequest.searchForm);
            if (tmpSearch.searchVal) {
                let regVal = new RegExp(tmpSearch.searchVal, "i"); //正式表达式模式查询
                tmpMatch.$or = [{ province_code: { $regex: regVal } }, { province_name: { $regex: regVal } }];
            }
        }
        await regionModel
            .aggregate([{ $match: tmpMatch }, { $count: "count" }])
            .then((result) => {
                console.log("count ", result);
                if (result && result[0]) {
                    //判断是否存在集合数量,使用 $count 查询
                    count = result[0].count;
                }
            })
            .catch((err) => {
                output(res, { code: 2, msg: "查询数据数量操作错误" + JSON.stringify(err) });
            });
        if (count > 0) {
            await regionModel
                .aggregate([
                    { $match: tmpMatch },
                    { $project: { _id: 0, province_code: 1, province_name: 1, create_time: 1 } },
                    { $skip: (parseInt(tmpRequest.page ?? 1) - 1) * parseInt(tmpRequest.pageNum ?? 30) },
                    { $limit: parseInt(tmpRequest.pageNum ?? 30) }
                ])
                .then((result) => {
                    //查询集合数据集
                    list = result;
                })
                .catch((err) => {
                    output(res, { code: 2, msg: "查询数据操作错误" + JSON.stringify(err) });
                });
        }
        output(res, { code: 1, msg: "成功", data: { count: count, list: list } });
        // res.render("region", { count: count, list: list });
    } catch (error) {
        output(res, { code: 2, msg: "操作错误" + JSON.stringify(error) });
    }
};
module.exports = { regionList };
